package com.bw.solr.solr02group;

import java.util.Collection;
import java.util.List;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.Group;
import org.apache.solr.client.solrj.response.GroupCommand;
import org.apache.solr.client.solrj.response.GroupResponse;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.params.GroupParams;
import org.junit.Before;
import org.junit.Test;

/**
 * Group分组，类似于Mysql的group By 
 * @author liuxing
 *
 */
public class GroupQuery {
	private HttpSolrClient client = null;

	@Before
	public void init() {
		// 获取solr连接，mycore1是集合名
		client = new HttpSolrClient("http://localhost:28080/solr/mycore");
		System.out.println(client);
	}

	@Test
	public void group() throws Exception {
		SolrQuery solrQuery = new SolrQuery("*:*");
		solrQuery.setParam(GroupParams.GROUP, true);
		// 设置Group查询针对的域
//		solrQuery.setParam(GroupParams.GROUP_FIELD, "category_s");
		solrQuery.setParam("group.field", "category_s");
//		solrQuery.set("group.field", "category_s");
//		solrQuery.setParam(GroupParams.GROUP_FIELD, "price");
		// 设置每个组最多返回的记录数，可用于数据采集;若只需要数量，可以设置为0
		solrQuery.setParam(GroupParams.GROUP_LIMIT, "1");
		// 设置返回的行数
		solrQuery.setRows(10);
		System.out.println(solrQuery.toString());

		QueryResponse qr = client.query(solrQuery, SolrRequest.METHOD.POST);
		qr.getResults();
		GroupResponse groupResponse = qr.getGroupResponse();
		if (groupResponse != null) {
			List<GroupCommand> groupList = groupResponse.getValues();
			for (GroupCommand groupCommand : groupList) {
				List<Group> groups = groupCommand.getValues();
				for (Group group : groups) {
					System.out.println("--------------------");
					System.out.println("分组名为：" + group.getGroupValue() + "，组内数据个数为：" + group.getResult().size());
					System.out.println("组内数据如下：");
					SolrDocumentList re = group.getResult();
					for (SolrDocument s : re) {
						Collection<String> fieldNames = s.getFieldNames();
						for (String name : fieldNames) {
							System.out.println("	 " + name + ":" + s.getFieldValue(name));
						}
						System.out.println("xxxxxxxxxx");
					}
				}
			}
		}
	}

}
